import 'package:flutter/material.dart';
import 'package:flutter_admin/api/odoo/res_partner_odoo_api.dart';
import 'package:flutter_admin/models/odoo/res_partner.dart';
import 'package:flutter_admin/pages/common/cry/cry_button_bar.dart';
import 'package:flutter_admin/pages/common/cry/cry_buttons.dart';
import 'package:flutter_admin/pages/common/cry/cry_data_table.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_input.dart';
import 'package:flutter_admin/pages/common/cry/model/order_item_model.dart';
import 'package:flutter_admin/pages/common/cry/model/page_model.dart';
import 'package:flutter_admin/pages/common/cry/model/response_body_api.dart';

class SipplierList extends StatefulWidget {
  SipplierList({Key? key}) : super(key: key);
  @override
  _SipplierListState createState() => _SipplierListState();
}

class _SipplierListState extends State<SipplierList> {
  final GlobalKey<CryDataTableState> tableKey = GlobalKey<CryDataTableState>();
  final GlobalKey<FormState> formKey = GlobalKey<FormState>();
  final GlobalKey<ScaffoldState> scaffoldStateKey = GlobalKey<ScaffoldState>();
  PageModel page =
      PageModel(orders: [OrderItemModel(column: 'create_date', asc: false)]);
  ResPartner resPartner = ResPartner();
  List<ResPartner> selectedList = [];
  bool flag = true;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance!.addPostFrameCallback((c) {
      _query();
    });
  }

  @override
  Widget build(BuildContext context) {
    var form = Form(
      key: formKey,
      child: Wrap(
        children: <Widget>[
          CryInput(
            width: 280,
            label: '供应商名称',
            value: resPartner.name,
            onSaved: (v) {
              resPartner.name = v;
            },
          ),
        ],
      ),
    );
    CryDataTable table = CryDataTable(
      key: tableKey,
      title: "数据列表",
      onPageChanged: (firstRowIndex) {
        page.current = (firstRowIndex ~/ page.size + 1);
        _loadData();
      },
      onRowsPerPageChanged: (int size) {
        page.size = size;
        page.current = 1;
        _loadData();
      },
      onSelectChanged: (Map selected) {
        if (flag) {
          Navigator.pop(context, selected);
        }
        flag = false;
      },
      columns: [
        DataColumn(label: Text('企业类型')),
        DataColumn(label: Text('供应商编码')),
        DataColumn(label: Text('用户名')),
        DataColumn(label: Text('供应商名称')),
        DataColumn(label: Text('供应商简称')),
        DataColumn(label: Text('供应商曾用名称')),
        DataColumn(label: Text('企业性质')),
        DataColumn(label: Text('邮编')),
        DataColumn(label: Text('电子邮件')),
        DataColumn(label: Text('企业电话')),
        DataColumn(label: Text('传真')),
        DataColumn(label: Text('公司办公地址')),
        DataColumn(label: Text('公司网站地址')),
        DataColumn(label: Text('生产工厂地址')),
        DataColumn(label: Text('开户银行')),
        DataColumn(label: Text('银行账号')),
        DataColumn(label: Text('公司法人姓名')),
        DataColumn(label: Text('法人联系方式')),
        DataColumn(label: Text('公司投资人姓名')),
        DataColumn(label: Text('各自投资比例')),
        DataColumn(label: Text('公司成立时间')),
        DataColumn(label: Text('税号')),
        DataColumn(label: Text('注册资金（万元）')),
        DataColumn(label: Text('固定资产（万元）')),
        DataColumn(label: Text('生产规模')),
        DataColumn(label: Text('所属行业')),
        DataColumn(label: Text('行业排序')),
        DataColumn(label: Text('银行资信证明')),
        DataColumn(label: Text('供货区域')),
        DataColumn(label: Text('所属地区')),
        DataColumn(label: Text('QQ')),
        DataColumn(label: Text('信函通讯地址')),
        DataColumn(label: Text('公司营业范围')),
        DataColumn(label: Text('产品品牌')),
        DataColumn(label: Text('业绩简介')),
        DataColumn(label: Text('企业简介')),
      ],
      getCells: (m) {
        ResPartner resPartner = ResPartner.fromMap(m);
        return [
          DataCell(Text(resPartner.businessType == '0'
              ? '供应商'
              : resPartner.businessType == '1'
                  ? '生产商'
                  : '--')),
          DataCell(Text(resPartner.ref ?? '--')),
          DataCell(Text(resPartner.userNameSupplier ?? '--')),
          DataCell(Text(resPartner.name ?? '--')),
          DataCell(Text(resPartner.supplierAbbreviation ?? '--')),
          DataCell(Text(resPartner.usedName ?? '--')),
          DataCell(Text(resPartner.person ?? '--')),
          DataCell(Text(resPartner.zip ?? '--')),
          DataCell(Text(resPartner.email ?? '--')),
          DataCell(Text(resPartner.phone ?? '--')),
          DataCell(Text(resPartner.faxes ?? '--')),
          DataCell(Text(resPartner.officeAddress ?? '--')),
          DataCell(Text(resPartner.website ?? '--')),
          DataCell(Text(resPartner.factoryAddress ?? '--')),
          DataCell(Text(resPartner.bank ?? '--')),
          DataCell(Text(resPartner.bankAccount ?? '--')),
          DataCell(Text(resPartner.primaryContact ?? '--')),
          DataCell(Text(resPartner.mobile ?? '--')),
          DataCell(Text(resPartner.investor ?? '--')),
          DataCell(Text(resPartner.investRatio ?? '--')),
          DataCell(Text(resPartner.regTime ?? '--')),
          DataCell(Text(resPartner.vat ?? '--')),
          DataCell(Text(resPartner.registerMoney != null
              ? resPartner.registerMoney.toString()
              : '--')),
          DataCell(Text(resPartner.fixedAssets != null
              ? resPartner.fixedAssets.toString()
              : '--')),
          DataCell(Text(resPartner.processScale ?? '--')),
          DataCell(Text(resPartner.industryName ?? '--')),
          DataCell(Text(resPartner.industrySort ?? '--')),
          DataCell(Text(resPartner.credibilityLetter ?? '--')),
          DataCell(Text(resPartner.areaName ?? '--')),
          DataCell(Text(resPartner.area ?? '--')),
          DataCell(Text(resPartner.qq ?? '--')),
          DataCell(Text(resPartner.postalAddress ?? '--')),
          DataCell(Text(resPartner.mainBusiness ?? '--')),
          DataCell(Text(resPartner.productBrand ?? '--')),
          DataCell(Text(resPartner.performanceProfile ?? '--')),
          DataCell(Text(resPartner.enterpriseProfile ?? '--')),
        ];
      },
    );
    _getSelectList();
    CryButtonBar buttonBar = CryButtonBar(
      children: <Widget>[
        CryButtons.query(context, () => _query()),
        CryButtons.reset(context, () => _reset()),
      ],
    );
    var result = Scaffold(
      appBar: AppBar(
        title: Text('供应单位'),
      ),
      key: scaffoldStateKey,
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          SizedBox(height: 10),
          form,
          buttonBar,
          Expanded(child: SingleChildScrollView(child: table)),
        ],
      ),
    );
    return result;
  }

  _reset() {
    resPartner = ResPartner();
    formKey.currentState!.reset();
    _loadData();
  }

  _query() {
    formKey.currentState?.save();
    tableKey.currentState?.pageTo(0);
    _loadData();
  }

  _loadData() async {
    ResponseBodyApi responseBodyApi = await ResPartnerOdooApi.page(
        data: {"page": page, "domainList": resPartner.toDomainList1()});
    if (responseBodyApi.success!) {
      page = responseBodyApi.data != null ? responseBodyApi.data : PageModel();
      tableKey.currentState!.loadData(page);
      _getSelectList();
    }
  }

  _getSelectList() {
    selectedList = tableKey.currentState
            ?.getSelectedList(page)
            .map<ResPartner>((e) => ResPartner.fromMap(e))
            .toList() ??
        [];
    setState(() {});
  }
}
